package cn.wolfcode.shiro;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.exception.LogicException;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.util.RepairPassword;
import cn.wolfcode.util.UserContext;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;

@Component
public class CrmRealm extends AuthorizingRealm {
    @Autowired
    private EmployeeMapper employeeMapper;


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取当前员工的对象
        //Employee employee = UserContext.getEmployee();
        Employee employee = (Employee)principalCollection.getPrimaryPrincipal();

        //创建权限认证器
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        System.out.println("我是权限器的数据源");
        //判断是否是超级管理员先,只要超级管理员就会拥有全部权限
        if (employee.isAdmin()){
            info.addStringPermission("*:*");
            //添加一个管理员角色,以便我们前端使用
            info.addRole("admin");
        }else {
            //查询出该员工下的所有角色
            List<String> sns = employeeMapper.selectSns(employee.getId());
            //添加到当前数据源中
            info.addRoles(sns);
            //查询出该员工下的所有权限
            List<String> expressions = employeeMapper.selectExpression(employee.getId());
            //封装到当前数据源中
            info.addStringPermissions(expressions);
        }
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取前端传过来的令牌中的用户名
        String username = (String) token.getPrincipal();
        UsernamePasswordToken token1 = (UsernamePasswordToken) token;
        System.out.println("我是认证器的数据源");
        char[] password = token1.getPassword();
        String s = String.valueOf(password);
        if (!StringUtils.hasText(username)){
            throw new LogicException("账号不能为空");
        }
        if (!StringUtils.hasText(s)){
            throw new LogicException("密码不能空");
        }
        //查询数据库中是否存在对应的员工
        Employee employee = employeeMapper.selectCheckName(username);
        System.out.println(employee);
        if (employee != null) {
            UserContext.setCurrentUser(employee);
            //判断账号是否被禁用
            if (!employee.isStatus()){
                throw new LogicException("账号已禁用");
            }

            //如果存在就返回一个
            return new SimpleAuthenticationInfo(employee, employee.getPassword(), this.getName());
        }
        //否则就返回报错,账号错误
        return null;
    }
}
